package com.zyg.cod.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.IOUtils;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;


/**
 * 文件相关工具类
 */
@Slf4j
public class FileUtils {


	/**
	 * 写入信息:打印
	 *
	 * @throws IOException
	 */
	public static void write(String url, List<String> strList) throws IOException {
		//设置字符编码
		OutputStreamWriter osw = null;
		BufferedWriter bufferedWriter = null;
		try {
			File file = new File(url);// 指定要写入的文件
			File fileParent = file.getParentFile();
			if (!fileParent.exists()) {
				fileParent.mkdirs();
			}
			boolean boo = file.createNewFile();
			if (!boo) {
				return ;
			}
			//设置字符编码
			osw = new OutputStreamWriter(new FileOutputStream(file),
					StandardCharsets.UTF_8);
			// 获取该文件的缓冲输出流
			bufferedWriter = new BufferedWriter(osw);
			for (int i = 0; i < strList.size(); i++) {
				// 写入信息
				if (i == 0) {
					bufferedWriter.write(strList.get(i));
				} else {
					bufferedWriter.write(strList.get(i));
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (bufferedWriter != null) {
				bufferedWriter.flush();// 清空缓冲区
				bufferedWriter.close();// 关闭输出流
			}

		}


	}

	/**
	 * 将string内容追加写到到目录里的文件上，不覆盖原来的数据
	 */
	public static void writeString2File2(String path, String str) throws Exception {
		FileWriter fwriter = null;
		try {
			// true表示不覆盖原来的内容，而是加到文件的后面。若要覆盖原来的内容，直接省略这个参数就好
			fwriter = new FileWriter(path, true);
			fwriter.write(str);
		} catch (IOException ex) {
			ex.printStackTrace();
		} finally {
			try {
				assert fwriter != null;
				fwriter.flush();
				fwriter.close();
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
	}

	/**
	 * 将string内容写到指定文件指定文件夹里
	 */
	public static void writeString2File(String path, String str) throws Exception {
		//如果指定路径不存在，创建
		File file = new File(path);
		File fileParent = file.getParentFile();
		if (!fileParent.exists()) {
			fileParent.mkdirs();
		}
		boolean boo = file.createNewFile();
		if (!boo) {
			return;
		}
		FileOutputStream fos = null;
		OutputStreamWriter osw = null;
		PrintWriter out = null;
		try {
			fos = new FileOutputStream(path, true);
			osw = new OutputStreamWriter(fos, StandardCharsets.UTF_8);
			out = new PrintWriter(osw);
			out.println(str);
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		} finally {
			IOUtils.closeQuietly(out);
			IOUtils.closeQuietly(osw);
			IOUtils.closeQuietly(fos);
		}

	}

	/**
	 * 得到指定路径下的所有文件，按文件修改时间(由小到大)返回文件集合
	 */
	public static List<File> getSortFilesByPath(String path) {
		List<File> fileList = new LinkedList<File>();
		//不递归文件夹得到所有文件
		fileList = getFilesByPath(path);
		//排序文件
		if (fileList.size() > 0) {
			fileList.sort(new Comparator<File>() {
				public int compare(File file, File newFile) {
					if (file.lastModified() > newFile.lastModified()) {
						return 1;//返回正值，按以上相反排序，即小的放前面
					} else if (file.lastModified() == newFile.lastModified()) {
						return 0;
					} else {
						return -1;
					}
				}
			});
		}
		return fileList;
	}

	/**
	 * 得到指定路径下的所有文件夹的所有文件
	 */
	public static List<File> getAllFilesByPath(String path) {
		List<File> fileList = new ArrayList<File>();
		File dir = new File(path);
		File[] files = dir.listFiles();
		if (files != null && files.length > 0) {
			for (int i = 0; i < files.length; i++) {
				if (files[i].isDirectory()) {
					getAllFilesByPath(files[i].getAbsolutePath());
				} else if (files[i].getName().toLowerCase().endsWith(".xml")) {
					fileList.add(files[i]);
				}
			}
		}
		return fileList;
	}

	/**
	 * 得到指定路径下的所有文件，不递归文件夹
	 */
	public static List<File> getFilesByPath(String path) {
		List<File> fileList = new ArrayList<File>();
		File dir = new File(path);
		File[] files = dir.listFiles();
		if (files != null && files.length > 0) {
			for (int i = 0; i < files.length; i++) {
				if (files[i].isDirectory()) {
					//不递归文件夹
				} else if (files[i].getName().toLowerCase().endsWith(".xml")) {//只获取xml文件
					fileList.add(files[i]);
				}
			}
		}
		return fileList;
	}

	/**
	 * 移动指定文件到指定目录，并删除原报文
	 */
	public static boolean moveAndDeleteFile(File file, String targetPath) throws Exception {
		//如果指定目录不存在，创建
		File f = new File(targetPath);
		if (!f.exists()) {
			f.mkdirs();
		}
		boolean flag = false;
		FileInputStream fis = null;
		InputStreamReader isr = null;
		BufferedReader read = null;
		OutputStreamWriter osw = null;
		PrintWriter out = null;
		try {
			fis = new FileInputStream(file);
			isr = new InputStreamReader(fis, StandardCharsets.UTF_8);
			read = new BufferedReader(isr);
			osw = new OutputStreamWriter(new FileOutputStream(targetPath + "\\" + file.getName()),
					StandardCharsets.UTF_8);
			out = new PrintWriter(osw);
			String readContent = null;
			while ((readContent = read.readLine()) != null) {
				out.println(readContent);
			}
			flag = true;
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception(file.getName() + "原报文删除失败！");
		} finally {
			IOUtils.closeQuietly(out);
			IOUtils.closeQuietly(osw);
			IOUtils.closeQuietly(read);
			IOUtils.closeQuietly(isr);
			IOUtils.closeQuietly(fis);
			//如果写没抛异常，删除源文件
			if (flag) {
				file.delete();
			}
		}
		return flag;
	}

	/**
	 * 复制文件
	 *
	 * @param file
	 * @param targetPath
	 * @return
	 * @throws Exception
	 */
	public static synchronized boolean copyFile(File file, String targetPath) throws Exception {
		File file1 = new File(targetPath);
		if (!file1.exists()) {
			file1.mkdirs();
		}
		boolean flag = true;
		FileInputStream fis = null;
		InputStreamReader isr = null;
		BufferedReader read = null;
		OutputStreamWriter osw = null;
		PrintWriter out = null;
		try {
			fis = new FileInputStream(file);
			isr = new InputStreamReader(fis, StandardCharsets.UTF_8);
			read = new BufferedReader(isr);
			osw = new OutputStreamWriter(new FileOutputStream(targetPath + "\\" + file
					.getName()), StandardCharsets.UTF_8);
			out = new PrintWriter(osw);
			String readContent = null;
			while ((readContent = read.readLine()) != null) {
				out.println(readContent);
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			IOUtils.closeQuietly(out);
			IOUtils.closeQuietly(osw);
			IOUtils.closeQuietly(read);
			IOUtils.closeQuietly(isr);
			IOUtils.closeQuietly(fis);
		}
		return flag;
	}

	/**
	 * 将file转为string
	 */
	public static String file2String(File file) {
		FileInputStream fis = null;
		InputStreamReader isr = null;
		BufferedReader buffer = null;
		try {
			fis = new FileInputStream(file);
			isr = new InputStreamReader(fis, StandardCharsets.UTF_8);
			buffer = new BufferedReader(isr);
			StringBuilder sb = new StringBuilder();
			String temp;
			while ((temp = buffer.readLine()) != null) {
				sb.append(temp);
			}
			return sb.toString();
		} catch (Exception e) {
			return "";
		} finally {
			IOUtils.closeQuietly(buffer);
			IOUtils.closeQuietly(isr);
			IOUtils.closeQuietly(fis);
		}
	}

	/**
	 * 文件删除
	 */
	/**
	 * 移动指定文件到指定目录，并删除原报文
	 */
	public static boolean deleteFile(File file, String targetPath) throws Exception {

		//根据文件文件路径查询是否存在该文件
		//删除数据库数据
		//存在则删除文件
		//不存在返回


		return false;
	}

	//重载方法
	public static String creatFilePath(String basePath) {
		StringBuilder stringBuilder = new StringBuilder();
		stringBuilder.append(basePath).append("/").append(com.csii.credit.util.DateUtil.getDateStr()).append("/");
		return stringBuilder.toString();
	}

	public static String creatFilePath(String basePath, String fileName) {
		StringBuilder stringBuilder = new StringBuilder();
		stringBuilder.append(basePath).append("/").append(com.csii.credit.util.DateUtil.getDateStr()).append("/").append(fileName);
		return stringBuilder.toString();
	}

}
